<?php
/**
 * Created by PhpStorm.
 * User: deng
 * Date: 2015/3/6
 * Time: 14:17
 */

namespace Serve\Controller;

use Common\Controller\NormalApiController;
use Think\Response;
use Serve\Utils\JWTToken;

vendor('Jwt.JWT');

class TokenController extends NormalApiController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function get()
    {
        if ($this->_method == 'options') {
            $this->options('Access-Control-Allow-Methods: POST, OPTIONS');
        }
        $username = $this->_request['username'];
        $password = $this->_request['password'];
        if (!$username || !$password)
            ClientError('缺少参数', C('CODE.BAD_REQUEST')['code']);
        $cond = ['auth' => ['username' => $username, 'password' => md5($password)]];
        $result = [];
        if ($userInfo = $this->checkAuth($this->_db->users, $cond)) {
            $result = array_merge($result, $userInfo);
        } else
            ClientError('用户密码错误', C('CODE.NOT_FOUND')['code']);
        if ($labs = $this->getUserLabs($this->_db->labs, $userInfo['userId'])) {
            $result['labIds'] = $labs;
        }
        $token = JWTToken::generateToken($result);
        $result['token'] = $token;
        Success(200, $data = $result);
    }

    public function update()
    {
        if ($this->_method == 'options') {
            $this->options('Access-Control-Allow-Methods: POST, OPTIONS');
        }
        $headers = getallheaders();
        if (empty($headers['X-Token']))
            ClientError('请求参数错误', C('CODE.BAD_REQUEST')['code']);
        else {
            $token = $headers['X-Token'];
            $array = JWTToken::parseToken($token);
            $model = $this->_db->users;
            if ($user = $model->find($array['userId'])) {
                if ($user['auth']['username'] == $array['username']) {
                    $result = [];
                    if ($userInfo = $this->getUserInfo($this->_db->users, $user['id'])) {
                        $result = array_merge($result, $userInfo);
                    } else
                        ClientError('用户密码错误', C('CODE.NOT_FOUND')['code']);
                    if ($labs = $this->getUserLabs($this->_db->labs, $result['userId'])) {
                        $result['labIds'] = $labs;
                    }
                    $result['token'] = JWTToken::generateToken($result);
                    Success(200, $data = $result);
                } else
                    ClientError('令牌非法', C('CODE.BAD_REQUEST')['code']);
            } else {
                ClientError('令牌非法', C('CODE.BAD_REQUEST')['code']);
            }
        }
    }

    private function checkAuth($model, $cond)
    {
        $result = [];
        if ($user = $model->findUnique($cond)) {
            $result['userId'] = $user['id'];
            $result['username'] = $user['auth']['username'];
            $result['role'] = $user['role'];
            $result['focusedLabs'] = $user['focusedLabs'];
        }
        return $result;
    }

    private function getUserInfo($model, $userId)
    {
        $result = [];
        if ($user = $model->find($userId)) {
            $result['userId'] = $user['id'];
            $result['username'] = $user['auth']['username'];
            $result['role'] = $user['role'];
            $result['focusedLabs'] = $user['focusedLabs'];
        }
        return $result;
    }

    private function getUserLabs($model, $userId)
    {
        $result = [];
        if ($labs = $model->findBy(['cond' => ['creatorId' => $userId]])['list']) {
            foreach ($labs as $key => $value) {
                $result[] = $value['id'];
            }
        }
        return $result;
    }
}